<template>
  <div class="container">
    <div class="search">
      <el-form :inline="true"  label-width="68px" size="small">
         <el-form-item label="管理员名">
            <el-input v-model="searchData.name" placeholder="管理员名"></el-input>
         </el-form-item>
         <el-form-item label="电话号码">
            <el-input v-model="searchData.phone" placeholder="电话号码"></el-input>
         </el-form-item>
         <el-form-item label="邮箱">
            <el-input v-model="searchData.email" placeholder="邮箱"></el-input>
         </el-form-item>
         <el-form-item label="登录名">
            <el-input v-model="searchData.username" placeholder="登录名"></el-input>
         </el-form-item>
      </el-form>
    </div>
    <div class="operation">
       <el-button type="primary" @click="search">搜索</el-button>
       <el-button type="primary" @click="handleAddStaff">添加</el-button>
    </div>
    <el-table :data="listData" style="width: 100%" :height="578">
      <el-table-column prop="name" label="姓名">
      </el-table-column>
      <el-table-column prop="email" label="邮箱">
      </el-table-column>
      <el-table-column prop="phone" label="电话号码">
      </el-table-column>
      <el-table-column prop="username" label="用户名">
      </el-table-column>
      <el-table-column prop="" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEditStaff(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleChangePassword(scope.row)">修改密码</el-button>
          <el-button size="mini" type="danger" @click="handleDeleteStaff(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page.pageNumber"
      :page-sizes="[10,20, 50, 100, 500]"
      :page-size="page.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.total">
    </el-pagination>
    <el-dialog
      title="添加管理员"
      :visible="dialog == 'addStaff'" :before-close="handleAddClose"
      width="30%">
      <el-form :inline="false" :model="addData" :rules="addStaffRule" ref="addStaff" label-width="68px" size="small" >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addData.name" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addData.email" placeholder="邮箱"></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="addData.phone" placeholder="电话号码"></el-input>
        </el-form-item>
        <el-form-item label="登录用户名" prop="username">
          <el-input v-model="addData.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addData.password" placeholder="密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="passwordCheck">
          <el-input v-model="addData.passwordCheck" placeholder="确认密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="拥有角色" >
          <el-autocomplete
             class="float-l"
            v-model="queryString"
            :fetch-suggestions="queryAddSearch"
            placeholder="请输入内容"
            :trigger-on-focus="false"
            @select="handleAddSelect"
          >
          <template slot-scope="{ item }">
            <div class="name">{{ item.name }}</div>
          </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="拥有角色" >
          <el-tag
            class="float-l margin-r-5"
            :key="role.id"
            v-for="role in addData.roles"
            closable
            :disable-transitions="false"
            @close="handleAddDisChooseRole(role)">
            {{role.name}}
          </el-tag>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog = '';clearAddData()">取 消</el-button>
        <el-button type="primary" @click="addStaff">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="编辑管理员"
      :visible="dialog == 'editStaff'" :before-close="handleEditClose"
      width="30%">
      <el-form :inline="false" label-position="left" :model="editData" :rules="editStaffRule" ref="editStaff" label-width="68px" size="small" >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editData.name" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editData.email" placeholder="邮箱"></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="editData.phone" placeholder="电话号码"></el-input>
        </el-form-item>
        <el-form-item label="拥有角色"  prop="roles" >
          <el-autocomplete
            class="float-l"
            v-model="queryString"
            :fetch-suggestions="queryAddSearch"
            placeholder="请输入内容"
            :trigger-on-focus="false"
            @select="handleEditSelect"
          >
          <template slot-scope="{ item }">
            <div class="name">{{ item.name }}</div>
          </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="拥有角色" >
            <el-tag
              class="float-l margin-r-5"
              :key="role.id"
              v-for="role in editData.roles"
              closable
              :disable-transitions="false"
              @close="handleEditDisChooseRole(role)">
              {{role.name}}
            </el-tag>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog = '';clearEditData()">取 消</el-button>
        <el-button type="primary" @click="editStaff">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="修改密码" width="30%"
      :visible="dialog == 'changePassword'" :before-close="handlechangePasswordClose">
       <el-form :inline="false" label-position="left" :model="changePasswordData" :rules="changePasswordRule" ref="editStaff" label-width="68px" size="small" >
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="changePasswordData.newPassword" placeholder="新密码" show-password></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog = '';clearchangePasswordData()">取 消</el-button>
        <el-button type="primary" @click="changePassword">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import commonRules from '@/utils/validate-rules.js'
import api from '@/config/server.js'
export default {
  data () {
    var validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }
    var validatePasswordCheck = (rule, value, callback) => {
      console.log(this.addData)
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.addData.password) {
        callback(new Error('两次输入密码不一致!'))
      }
      callback()
    }
    return {
      // page: 0,
      // size: 20,
      listData: [],
      permissions: null,
      searchData: {
        name: '',
        phone: '',
        email: '',
        username: ''
      },
      addData: {
        name: '',
        email: '',
        phone: '',
        username: '',
        password: '',
        passwordCheck: '',
        roles: []
      },
      editData: {
        name: '',
        email: '',
        phone: '',
        username: '',
        password: '',
        roles: []
      },
      dialog: '',
      page: {
        pageNumber: 1,
        pageSize: 10,
        total: 0,
        totalPage: 0
      },
      defaultProps: {
        children: 'child',
        label: 'name'
      },
      addStaffRule: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        email: [
          commonRules.email
        ],
        phone: [
          commonRules.phone
        ],
        username: [
          { required: true, message: '请输入角色登录名', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        password: [
          {validator: validatePassword, trigger: 'blur'}
        ],
        passwordCheck: [
          {validator: validatePasswordCheck, trigger: 'blur'}
        ]
      },
      editStaffRule: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        email: [
          commonRules.email
        ],
        phone: [
          commonRules.phone
        ],
        username: [
          { required: true, message: '请输入角色登录名', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ]
      },
      changePasswordRule: {
        newPassword: [
          {validator: validatePassword, trigger: 'blur'}
        ]
      },
      changePasswordData: {
        id: null,
        newPassword: ''
      },
      queryString: ''
    }
  },
  created () {
    this.search()
  },
  methods: {
    search () {
      api.staffList({
        page: this.page.pageNumber - 1,
        size: this.page.pageSize,
        name: this.searchData.name,
        phone: this.searchData.phone,
        email: this.searchData.email,
        username: this.searchData.username
      }).then((res) => {
        this.listData = res.result.content
        this.page.pageNumber = res.result.pageable.pageNumber + 1
        this.page.pageSize = res.result.pageable.pageSize
        this.page.total = res.result.totalElements
        this.page.totalPage = res.result.totalPages
      })
    },
    handleAddStaff () {
      this.dialog = 'addStaff'
    },
    addStaff () {
      this.$refs['addStaff'].validate((valid) => {
        if (valid) {
          api.addStaff({
            name: this.addData.name,
            email: this.addData.email,
            phone: this.addData.phone,
            username: this.addData.username,
            password: this.addData.password,
            roles: this.addData.roles.map(role => {
              return role.id
            })
          }).then((res) => {
            if (res.ret === 1) {
              this.$message('添加成功')
              this.clearAddData()
              this.dialog = ''
              this.search()
            } else {
              this.$message(res.msg)
            }
          })
        }
      })
    },
    clearAddData () {
      this.addData = {
        name: '',
        email: '',
        phone: '',
        username: '',
        password: '',
        roles: []
      }
    },
    handleAddClose () {
      this.clearAddData()
      this.dialog = ''
    },
    queryAddSearch (queryString, cb) {
      api.roleSuggest({
        queryString: queryString
      }).then((res) => {
        cb(res.result)
      })
    },
    handleAddSelect (item) {
      let has = false
      for (let i = 0; i < this.addData.roles.length; i++) {
        if (this.addData.roles[i].id === item.id) {
          has = true
        }
      }
      if (!has) {
        this.addData.roles.push(item)
      }
    },
    handleAddDisChooseRole (staff) {
      this.addData.roles.splice(this.addData.roles.indexOf(staff), 1)
    },
    handleEditStaff (staff) {
      api.staffDetail(staff.id).then((res) => {
        this.editData = res.result
        this.dialog = 'editStaff'
      })
    },
    handleEditClose () {
      this.dialog = ''
      this.clearEditData()
    },
    clearEditData () {
      this.editData = {
        name: '',
        email: '',
        phone: '',
        username: '',
        password: '',
        roles: []
      }
    },
    handleEditSelect (item) {
      let has = false
      for (let i = 0; i < this.editData.roles.length; i++) {
        if (this.editData.roles[i].id === item.id) {
          has = true
        }
      }
      if (!has) {
        this.editData.roles.push(item)
      }
    },
    handleEditDisChooseRole (staff) {
      this.editData.roles.splice(this.editData.roles.indexOf(staff), 1)
    },
    editStaff () {
      this.$refs['editStaff'].validate((valid) => {
        if (valid) {
          api.editStaff(
            this.editData.id
            , {
              name: this.editData.name,
              email: this.editData.email,
              phone: this.editData.phone,
              username: this.editData.username,
              password: this.editData.password,
              roles: this.editData.roles.map(role => {
                return role.id
              })
            }).then((res) => {
            if (res.ret === 1) {
              this.$message('修改成功')
              this.clearEditData()
              this.dialog = ''
              this.search()
            } else {
              this.$message(res.msg)
            }
          })
        }
      })
    },
    handleChangePassword (row) {
      this.dialog = 'changePassword'
      this.changePasswordData.id = row.id
    },
    handlechangePasswordClose () {
      this.dialog = ''
      this.clearchangePasswordData()
    },
    clearchangePasswordData () {
      this.changePasswordData = {
        id: null,
        newPassword: ''
      }
    },
    changePassword () {
      api.changePassword(this.changePasswordData.id, {
        newPassword: this.changePasswordData.newPassword
      }).then((res) => {
        if (res.ret === 1) {
          this.$message('修改成功')
          this.dialog = ''
          this.clearchangePasswordData()
        } else {
          this.$message(res.msg)
        }
      })
    },
    handleDeleteStaff (row) {
      this.$confirm('确定删除角色?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.deleteStaff(row.id).then((res) => {
          if (res.ret === 1) {
            this.$message('删除成功')
            this.search()
          } else {
            this.$message(res.msg)
          }
        })
      }).catch(() => {
        // this.$message({
        //   type: 'info',
        //   message: '已取消删除'
        // });
      })
    },
    appendChild (ids, result) {
      for (let i = 0; i < result.length; i++) {
        let permission = result[i]
        if (permission.parentId) {
          ids.push(permission.id)
        }
        if (permission.child) {
          this.appendChild(ids, permission.child)
        }
      }
    },
    handleSizeChange (val) {
      this.page.pageSize = val
      this.search()
    },
    handleCurrentChange (val) {
      this.page.pageNumber = val
      this.search()
    },
    currentPage () {

    }
  }
}
</script>

<style lang="scss" scoped>
  .container{
    padding: 10px 0 0 0 ;
  }
  .search{
    .el-form{
      width:100%;
      display:flex;
      flex-direction:row;
      justify-content:flex-start;
      flex-wrap:wrap;
      .el-form-item{
        width: 270px;
      }
    }
    width:100%;
  }
  .operation{
    margin-top:10px;
    float: left;
  }
  .el-tree{
    width:200px;
  }
  .float-l{
    float: left;
  }
  .margin-r-5{
    margin-right: 5px;
  }
  // .el-input {
  //   width: 200px;
  // }

</style>>
